package org.u2ml.app.business.impl;

import java.util.List;

import javax.ws.rs.QueryParam;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.u2ml.app.business.ProjectClassService;
import org.u2ml.app.domain.Oid;
import org.u2ml.app.domain.Project;
import org.u2ml.app.domain.ProjectClass;

@Component
@Transactional
public class ProjectClassServiceImpl implements ProjectClassService {

	@Autowired
	private SessionFactory sessionFactory;
	
	@SuppressWarnings("unchecked")
	public List<ProjectClass> get() {
		List<ProjectClass> list = sessionFactory.getCurrentSession()
    	.createQuery("from ProjectClass")
    	.list();
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<ProjectClass> getByProject(Project project) {
		List<ProjectClass> list = 
			sessionFactory.getCurrentSession()
			.createQuery("from ProjectClass c where c.project = :project")
			.setParameter("project", project)
			.list();
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public ProjectClass find(@QueryParam("oid") Long oid) {
		List<ProjectClass> list = sessionFactory.getCurrentSession()
        	.createQuery("from ProjectClass projectclass where projectclass.oid = :oid")
        	.setParameter("oid",oid)
        	.list();
		return (list.size()==0) ? null : list.get(0);
	}

	@SuppressWarnings("unchecked")
	public ProjectClass findByName(@QueryParam("name") String name) {
		List<ProjectClass> list = sessionFactory.getCurrentSession()
    	.createQuery("from ProjectClass projectclass where projectclass.name = :name")
    	.setParameter("name",name)
    	.list();
	return (list.size()==0) ? null : list.get(0);
	}

	public ProjectClass save(ProjectClass c) {
		sessionFactory.getCurrentSession().save(c);
		return c;
	}

	public ProjectClass update(ProjectClass c) {
		sessionFactory.getCurrentSession().update(c);
		return c;
	}	
	
	public void delete(ProjectClass c) {
		sessionFactory.getCurrentSession().delete(c);
	}
	
	@SuppressWarnings("unchecked")
	public boolean isParent(Long childOid, Long parentOid) {
		Session session = sessionFactory.getCurrentSession();
		List<ProjectClass> children = 
			session.createQuery("from ProjectClass c where c.oid = :oid")
			.setParameter("oid", childOid)
			.list();
		if (children.size()==0)
			return false;
		ProjectClass child = children.get(0);
		
		List<Oid> parents = 
			session.createQuery("from Oid oid where oid.value = :value")
			.setParameter("value", parentOid)
			.list();
		if (parents.size()==0)
			return false;
		Oid parent = parents.get(0);
	
		return child.getParents().contains(parent);
	}
}
